package cn.com.fattiger.framework.cms.admin.common.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.com.fattiger.framework.cms.admin.common.model.User;
import cn.com.fattiger.framework.cms.admin.common.model.Version;
import cn.com.fattiger.framework.cms.admin.common.service.RedisService;
import cn.com.fattiger.framework.cms.admin.common.service.VersionService;
import cn.com.fattiger.framework.cms.config.CustomConfig;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author fattiger.xiaoyang
 * @date 2016/05/05
 */
@Controller
@RequestMapping("version")
public class VersionController {
	
	private final Logger logger = Logger.getLogger(getClass());
	@Autowired
	VersionService versionService;
	@Autowired
    private CustomConfig customConfig;
	@Autowired
	private RedisService redisServer;
	
	@RequestMapping("list.do")
	public String getListPage(Integer page, Integer pageSize, String appName, Integer fileType, Integer status, ModelMap map){
		if(page == null || page < 0){
			page = 0;
		}
		if(pageSize == null || pageSize < 0 || pageSize > 100){
			pageSize = 10;
		}
		Map<String, String> condition = new HashMap<String, String>();
		if(null != appName && !"".equals(appName)){
			condition.put("appName",appName);
		}
		if(null != fileType){
			condition.put("fileType",fileType.toString());
		}
		if(null != status){
			condition.put("status",status.toString());
		}
		Page<Version> pageList = versionService.list(page, pageSize, condition);
		map.put("versions", 	pageList.getContent());
    	map.put("totalPageNum", pageList.getTotalPages());
    	map.put("currentPage", 	pageList.getNumber());
    	map.put("totalNum", 	pageList.getTotalElements());
		map.put("appName",		appName);
		map.put("fileType",		fileType);
		map.put("status",		status);
		return "version/version_list";
	}
	
	@RequestMapping(value = "save.do", method = RequestMethod.POST)
	public String save(@RequestParam("file") MultipartFile uploadFile, Version entity, HttpServletRequest request){
		if(uploadFile != null && !"".equals(uploadFile.getOriginalFilename())){
			String fileName = uploadFile.getOriginalFilename();
			String toDir = customConfig.getUploadRoot_app();
			File toDirFile = new File(toDir);
			if (!toDirFile.exists()) {
				toDirFile.mkdirs();
	 		}
	 		File toFile = new File(toDir + File.separator + fileName);
	 		try {
				uploadFile.transferTo(toFile);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	 		entity.setFileUrl(fileName);
	 		entity.setFileSize(uploadFile.getSize());
		}
 		User u = (User)request.getSession().getAttribute("__USER__");
 		if (entity.getId() != null) {
 			Version oldEntity = versionService.get(entity.getId());
 			if(entity.getFileSize()== null || entity.getFileSize() == 0){
 				entity.setFileSize(oldEntity.getFileSize());
 			}
 			entity.setUpdateTime(new Date());
 			entity.setUpdateUser(u.getName());
 			entity.setStatus(oldEntity.getStatus());
 			entity.setCreateTime(oldEntity.getCreateTime());
			entity.setCreateUser(oldEntity.getCreateUser());
		} else {
			if(entity.getFileType() == 1){
				entity.setPatchCode(null);
				entity.setPatchName(null);
			}
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			entity.setUpdateUser(u.getName());
			entity.setStatus(1);
		}
		ObjectMapper mapper = new ObjectMapper();
	    String json = null;
 		try {
 			json = mapper.writeValueAsString(entity);
 		} catch (JsonProcessingException e) {
 			logger.error(e.getMessage(),e);
 		}
 		logger.info(json);
        versionService.save(entity);
		return "redirect:list.do";
	}
	
	@RequestMapping(value = "update.do", method = RequestMethod.POST)
	public String update(Version entity, HttpServletRequest request){
 		User u = (User)request.getSession().getAttribute("__USER__");
		entity.setUpdateTime(new Date());
		entity.setUpdateUser(u.getName());
        versionService.updateChangeLog(entity.getId(), entity.getChangeLog());
		return "redirect:list.do";
	}
	
	@RequestMapping(value = "status.do", method = RequestMethod.GET)
	public String changeStatue(Integer id, Integer status, Integer page){
		versionService.updateStauts(id, status);
		return "redirect:list.do?page=" + page;
	}
	
	@RequestMapping(value = "del.do", method = RequestMethod.GET)
	public String del(Integer id,  Integer page){
		versionService.delete(id);
		return "redirect:list.do?page=" + page;
	}
	
	@RequestMapping(value = "edit.do", method = RequestMethod.GET)
	public String edit(Integer id, Integer page, ModelMap map){
		Version version = null;
		if(null != id){
			version = versionService.get(id);
		}
		map.put("version", version);
		map.put("page", page);
		return "version/version_edit";
	}
	@RequestMapping(value= "getCode.do", method = RequestMethod.GET)
	@ResponseBody
	public Integer getCode(String appKey, Integer fileType, Integer versionCode){
		if(fileType == 1){
			versionCode = null; 
		}
		return versionService.getCode(appKey, versionCode);
	}
	
	@RequestMapping(value = "view.do", method = RequestMethod.GET)
	public String view(Integer id, Integer page, ModelMap map){
		Version version = versionService.get(id);
		map.put("version", version);
		map.put("page", page);
		return "version/version_view";
	}
	
}
